<template>
  <view class="container">
    <view class="page-wrapper">
      <view class="agent-list" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20rpx;">
        <view class="agent-item" v-for="item in items" :key="item.id" :style="{
          backgroundImage: `url(${item.image_url})`,
          height: '380rpx',
          borderRadius: '5%'
        }">
          <view class="content-overlay"
            style="display: flex; flex-direction: column; justify-content: flex-end; height: 100%; padding-bottom: 10px; background: linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 50%, transparent 100%);">
            <text class="agent-name">{{ item.name || item.title }}</text>
            <text class="agent-info">{{ item.description || '暂无描述' }}</text>
            <view class="btn-wrapper">
              <button class="buy-btn optimized" @click="handleBuy(item)">
                <text class="btn-text" v-if="!item.is_purchased">立即购买</text>
                <text class="btn-text purchased" v-else>已购买</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <payment-dialog ref="paymentDialogref" :qrcode-url="currentQrcode" :wechat-nickname="wechatNickname"
    @confirm="handlePaymentSuccess" />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import PaymentDialog from '@/components/PaymentDialog.vue';
import { useUserStore } from '@/stores/userdata';
import { usePayment } from '@/components/useParment';

const API_BASE_URL = 'https://37ace603.r34.cpolar.top';
const items = ref([]);
const loading = ref(false);
const userStore = useUserStore();
const { handlePayment } = usePayment();
// 弹框
const currentQrcode = ref('')
const wechatNickname = ref(userStore.userData.username || '未设置昵称')
const paymentDialogref = ref(null)

// 监听用户数据变化
watch(() => userStore.userData.nickname, (newNickname) => {
  wechatNickname.value = newNickname || '未设置昵称';
});

// 显示支付弹窗
const showPaymentDialog = async (item) => {
  try {
    console.log('开始生成支付订单，商品信息:', item);
    
    // 检查必要参数
    if (!item.product_id && !item.id) {
      throw new Error('商品ID不能为空');
    }
    
    if (!userStore.userData.phone) {
      throw new Error('请先绑定手机号');
    }

    const requestData = {
      product_id: item.product_id || item.id,
      phone: userStore.userData.phone,
      openid: userStore.userData.openid || '',
      amount: item.price || 0,
      title: item.name || item.title || '商品购买'
    };

    console.log('支付请求数据:', requestData);

    // 生成订单二维码
    const qrcodeRes = await uni.request({
      url: `${API_BASE_URL}/payments/`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${userStore.userData.access_token}`,
        'content-type': 'application/json'
      },
      data: requestData
    });

    // 检查响应状态
    if (qrcodeRes.statusCode !== 200) {
      throw new Error(`服务器响应错误: ${qrcodeRes.statusCode}, ${JSON.stringify(qrcodeRes.data)}`);
    }

    // 检查响应数据
    if (!qrcodeRes.data) {
      throw new Error('服务器返回数据为空');
    }

    // 检查二维码URL
    if (!qrcodeRes.data.qrcode_url) {
      throw new Error('未获取到支付二维码URL');
    }

    // 设置二维码并打开弹窗
    currentQrcode.value = qrcodeRes.data.qrcode_url;
    paymentDialogref.value.openDialog();

  } catch (error) {
    console.error('生成订单二维码失败，详细信息:', {
      error: error.message,
      stack: error.stack,
      userData: {
        hasPhone: !!userStore.userData.phone,
        hasToken: !!userStore.userData.access_token,
        hasOpenid: !!userStore.userData.openid
      }
    });

    // 根据不同错误类型显示不同提示
    let errorMessage = '生成订单二维码失败';
    if (error.message.includes('商品ID不能为空')) {
      errorMessage = '商品信息无效';
    } else if (error.message.includes('请先绑定手机号')) {
      errorMessage = '请先绑定手机号';
    } else if (error.message.includes('服务器响应错误')) {
      errorMessage = '服务器响应异常，请稍后重试';
    }

    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 2000
    });
  }
}

// 支付成功处理
const handlePaymentSuccess = async () => {
  try {
    // 刷新商品列表以更新购买状态
    await loadProducts();
    
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('刷新商品列表失败:', error);
  }
}

// 检查用户登录状态
// const isUserLoggedInAndBoundPhone = () => {
  
//   return ;
// };
// console.log(isUserLoggedInAndBoundPhone)
// 加载商品数据
const loadProducts = async () => {
  loading.value = true;
  console.log('[关键节点] 开始加载商品数据');

  try {
    // 1. 获取商品列表
    const productsRes = await uni.request({
      url: 'https://37ace603.r34.cpolar.top/products/',
      method: 'GET'
    });

    if (productsRes.statusCode === 200 && Array.isArray(productsRes.data)) {
      console.log('[商品数据]', productsRes.data);
      items.value = productsRes.data.map(product => ({
        ...product,
        id: product.product_id,
        image_url: product.image_url || 'https://images.unsplash.com/photo-1620712943543-bcc4688e7485?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80',
        is_purchased: false
      }));

      // 2. 检查购买状态
      if (!!userStore.userData.access_token && !!userStore.userData.phone) {
        const userStore = useUserStore();
        await Promise.all(items.value.map(async (item) => {
          try {
            const checkRes = await uni.request({
              url: `${API_BASE_URL}/product-check/?product_id=${item.id}&phone=${userStore.userData.phone}`,
              method: 'GET',
              header: {
                'Authorization': `Bearer ${userStore.userData.access_token}`
              }
            });

            if (checkRes.statusCode === 200) {
              item.is_purchased = checkRes.data?.exists || false;
            }
          } catch (err) {
            console.error('检查购买状态失败:', err);
          }
        }));
      }
    }
  } catch (err) {
    console.error('[错误] 加载商品失败:', err);
    uni.showToast({ title: '获取商品失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 购买按钮点击事件
const handleBuy = async (item) => {
  console.log('[购买商品]', item);
  
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '提示',
      content: '请先登录并绑定手机号后才能购买',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.switchTab({ url: '/views/my/index' });
        }
      }
    });
    return;
  }

  if (!userStore.userData.phone) {
    uni.showModal({
      title: '提示',
      content: '请先绑定手机号',
      confirmText: '去绑定',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/views/myInfor/index' });
        }
      }
    });
    return;
  }

  // 如果已经购买，提示用户
  if (item.is_purchased) {
    uni.showToast({
      title: '您已购买过此商品',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: '正在创建订单...'
    });
    
    // 直接调用支付弹窗
    await showPaymentDialog(item);
  } catch (error) {
    console.error('支付流程错误:', error);
    uni.showToast({
      title: '支付流程异常，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 初始化加载
onMounted(() => {
  loadProducts();
});
</script>

<style scoped>
/* 容器样式 */
.container {
  padding: 24rpx;
  background:
    linear-gradient(135deg, #0a0e17 0%, #1a1f2e 100%),
    repeating-linear-gradient(45deg,
      rgba(56, 182, 255, 0.05) 0px,
      rgba(56, 182, 255, 0.05) 2px,
      transparent 2px,
      transparent 4px);
  min-height: 100vh;
  color: #e0e0e0;
}

/* 商品卡片 */
.card {
  background: rgba(255, 255, 255, 0.08);
  border-radius: 16rpx;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(56, 182, 255, 0.2);
  box-shadow:
    0 0 15px rgba(56, 182, 255, 0.1),
    inset 0 0 10px rgba(56, 182, 255, 0.05);
  transition: all 0.3s ease;
  min-height: 240rpx;
}

.card:active {
  transform: translateY(4rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 文字内容区域 */
.content {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.title {
  font-size: 34rpx;
  font-weight: 600;
  color: #38b6ff;
  margin-bottom: 12rpx;
  position: relative;
  padding-left: 20rpx;
  text-shadow: 0 0 5px rgba(56, 182, 255, 0.3);
}

.title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 24rpx;
  background: linear-gradient(to bottom, #38b6ff, #00e5ff);
  border-radius: 4rpx;
  box-shadow: 0 0 5px rgba(56, 182, 255, 0.5);
}

.status {
  font-size: 26rpx;
  color: #00e5ff;
  background: rgba(56, 182, 255, 0.15);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  display: inline-block;
  width: fit-content;
  border: 1px solid rgba(56, 182, 255, 0.3);
  animation: pulse 2s infinite;
}

/* 购买按钮 */
.buy-btn {
  background: #0b405e;
  color: #fff;
  border: none;
  border-radius: 30rpx;
  padding-top: 8px;
  padding-bottom: 8px;
  font-size: 22rpx;
  line-height: 1.2;
  margin-top: 10rpx;
  box-shadow: 0 0 10px rgba(11, 64, 94, 0.3);
  transition: all 0.3s ease;
  align-self: center;
  text-shadow: 0 0 5px rgba(11, 64, 94, 0.5);
  width: 60%;
  margin-bottom: 5px;
}

/* 按钮点击效果 */
.buy-btn:active {
  transform: scale(0.96);
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.5);
}

.card:hover {
  border-color: rgba(56, 182, 255, 0.4);
  box-shadow:
    0 0 25px rgba(56, 182, 255, 0.2),
    inset 0 0 15px rgba(56, 182, 255, 0.1);
}

/* 加载动画 */
@keyframes pulse {
  0% {
    opacity: 0.6;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.6;
  }
}

.loading-item {
  animation: pulse 1.5s infinite;
}
</style>
